package com.lizhivscaomei.dueros.tobaccoguider.repo;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lizhivscaomei.dueros.tobaccoguider.entity.TobaccoInfo;
import com.lizhivscaomei.dueros.tobaccoguider.mapper.TobaccoInfoMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@AllArgsConstructor
@Service("TobaccoInfoRepoMysql")
public class TobaccoInfoRepoMysql implements TobaccoInfoRepo {
    TobaccoInfoMapper mapper;

    @Override
    public List<TobaccoInfo> list(TobaccoInfo params) {
        LambdaQueryWrapper<TobaccoInfo> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(params.getCompany())) {
            query.eq(TobaccoInfo::getCompany, params.getCompany());
        }
        if (StringUtils.isNotEmpty(params.getSizeType())) {
            if ("爆珠".equalsIgnoreCase(params.getSizeType())) {
                query.eq(TobaccoInfo::getIsBall, params.getSizeType());
            } else {
                query.eq(TobaccoInfo::getSizeType, params.getSizeType());
            }
        }
        if (StringUtils.isNotEmpty(params.getBrand())) {
            query.eq(TobaccoInfo::getBrand, params.getBrand());
        }
        if (params.getSmallSalePrice() > 0) {
            double price = params.getSmallSalePrice();
            if (price < 50) {
                query.eq(TobaccoInfo::getSmallSalePrice, price);
            } else if (price >= 50 && price <= 100) {
                query.between(TobaccoInfo::getSmallSalePrice, price - 5, price + 5);
            } else if (price <= 500) {
                query.between(TobaccoInfo::getSmallSalePrice, price - 10, price + 10);
            } else {
                query.between(TobaccoInfo::getSmallSalePrice, price - 50, price + 50);
            }
        }
        query.orderByAsc(TobaccoInfo::getTypeOrderCode);
        return this.mapper.selectList(query);
    }

    @Override
    public Optional<TobaccoInfo> detail(TobaccoInfo query) {
        LambdaQueryWrapper<TobaccoInfo> queryWrapper = new LambdaQueryWrapper<TobaccoInfo>().eq(TobaccoInfo::getBrand, query.getBrand()).eq(TobaccoInfo::getSpec, query.getSpec());
        List<TobaccoInfo> introduceList = this.mapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(introduceList)) {
            return Optional.ofNullable(introduceList.get(0));
        }
        return Optional.empty();
    }

    @Override
    public TobaccoInfo findByBoxCode(String boxCode) {
        LambdaQueryWrapper<TobaccoInfo> queryWrapper = new LambdaQueryWrapper<TobaccoInfo>()
                .eq(TobaccoInfo::getSmallBoxCode, boxCode);
        return this.mapper.selectOne(queryWrapper);

    }
}
